﻿using System.ComponentModel;
using System.Collections.Generic;
using Inovout.Descriptors;
using System;
using System.Windows.Input;
using Inovout.Gui.Wpf.Commands;
using System.Linq;
using System.Collections;

namespace Inovout.Gui.Wpf.ViewModels
{
    public abstract class ModelViewModel : DomainViewModel, IDataErrorInfo, IEditableObject
    {
        private ClassDescriptor modelDescriptor;
        private Type modelType;
        protected ModelViewModel(Type modelType)
        {
            this.modelType = modelType;
            modelDescriptor = ClassDescriptor.Create(modelType);
        }

        public ICommand SaveCommand
        {
            get { return GetCommand(GetPropertyName(()=>SaveCommand)); }
        }
        protected override string[] CreateCommandNames()
        {
            return new string[] { 
          GetPropertyName(()=>this.SaveCommand)
            };
        }

        public event EventHandler<ModelAddedEventArgs> ModelAdded;

        protected virtual void OnModelAdded()
        {
            if (ModelAdded != null)
            {
                ModelAdded(this, new ModelAddedEventArgs(this));
            }
        }

        public string Error
        {
            get { return "Hello World!"; }
        }

        public string this[string propertyName]
        {
            get { return propertyName; }
        }

        protected Dictionary<string, object> savedState;

        public void BeginEdit()
        {
            OnBeginEdit();
            savedState = modelDescriptor.GetPropertyValues(ViewData.Model);
        }
        protected virtual void OnBeginEdit()
        {
        }
        public void CancelEdit()
        {
            if (savedState != null)
            {
                OnCancelEdit();
                modelDescriptor.SetPropertyValues(ViewData.Model, savedState);
                savedState = null;
            }
        }
        protected virtual void OnCancelEdit()
        {
        }
        public void EndEdit()
        {
            OnEndEdit();
            savedState = null;
        }
        protected virtual void OnEndEdit()
        {
        }

    }
}
